<?php
namespace app\common\model;

use think\Db;

class CmsFieldModel extends BaseModel
{

    protected $name = 'cms_field'; //定义用户表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    //类型自动转换
    protected $type = [
        'set'      => 'json',
        'validate' => 'json',
    ];
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    private $cmsMoudleModel;
    private $cmsMoudleCache;

    //自定义初始化
    protected function initialize()
    {
        parent::initialize();
        $this->cmsMoudleModel = new CmsMoudleModel();
        $this->cmsMoudleCache = cache('cms_moudle');
    }

    /*读取器*/
    protected function getIsSystemTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-danger">否</span>',
            1 => '<span class="label label-success">是</span>',
        ];
        return $status[$data['is_system']];
    }

    /*修改器*/
    protected function setFieldNameAttr($value)
    {
        return strtolower($value);
    }

    //不允许删除的字段
    public function noAllowDelete()
    {
        return ['title', 'thumb', 'cid', 'flag', 'sort', 'status', 'keywords', 'redirecturl', 'description', 'content', 'content_tpl', 'atlas', 'create_time','click'];
    }

    //不允许编辑的字段
    public function noAllowEdit()
    {
        return ['cid', 'flag', 'tag'];
    }

    //不允许禁用的字段
    public function noAllowForbidden()
    {
        return ['title', 'cid', 'status'];
    }

    /**
     * 获取验证器规则
     */
    public function getValidateRule()
    {
        $validateRule = [
            'require'     => '必填',
            'number'      => '数字',
            'float'       => '浮点数',
            'email'       => 'email',
            'date'        => '日期',
            'alpha'       => '字母',
            'alphaNum'    => '字母数字',
            'alphaDash'   => '字母数字下划线',
            'url'         => '超级链接',
            'chs'         => '汉字',
            'chsAlpha'    => '汉字字母',
            'chsAlphaNum' => '汉字字母数字',
            'chsDash'     => '汉字字母数字下划线破折号',
        ];
        return $validateRule;
    }

    /**
     * 添加字段
     */
    public function addData($data)
    {
        $table = $this->cmsMoudleModel->where('mid', $data['mid'])->value('table_name');
        if ($data['table_type'] == 1) {
            $prefixTable = config('database.prefix') . $table; //带前缀主表
        } else {
            $prefixTable = config('database.prefix') . $table . '_data'; //带前缀附表
            $table       = $table . '_data';
        }
        $fieldName = $data['field_name']; //字段名
        $fields    = array_keys(Db::getFields($prefixTable));
        if (in_array($fieldName, $fields)) {
            $this->error = '该字段名已存在!';
            return false;
        }
        switch ($data['field_type']) {
            case 'input': //文本框
                $length = $data['set']['length'];
                $sql    = "ALTER TABLE {$prefixTable} ADD {$fieldName} VARCHAR({$length}) NOT NULL DEFAULT ''";
                $data['i_field_type'] = 'string';
                break;
            case 'box':
                $set    = $data['set'];
                $length = $data['set']['length'];
                if ($set['field_type'] == 'vachar') {
                    if (empty($length)) $length = '255';
                    $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName}  VARCHAR({$length}) NOT NULL DEFAULT ''";
                    $data['i_field_type'] = 'string';
                } else {
                    if (empty($length)) $length = 4;
                    $fieldSet = " {$set['field_type']}({$length}) NOT NULL DEFAULT 0";
                    $sql      = "ALTER TABLE {$prefixTable} ADD {$fieldName} {$fieldSet} ";
                    $data['i_field_type'] = 'int';
                }
                break;
            case 'number':
                $set = $data['set'];
                if ($set['field_type'] == 'decimal') {
                    $e        = isset($set['num_decimal']) ? $set['num_decimal'] : 0;
                    $fieldSet = " DECIMAL({$set['num_integer']},{$e}) NOT NULL DEFAULT 0";
                    $data['i_field_type'] = 'float';
                } else {
                    $fieldSet = " {$set['field_type']}({$set['num_integer']}) NOT NULL DEFAULT 0";
                    $data['i_field_type'] = 'int';
                }
                $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName} {$fieldSet} ";
                break;
            case 'image':
            case 'file':
            case 'textarea':
                $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName}  VARCHAR(255) NOT NULL DEFAULT '' ";
                $data['i_field_type'] = 'string';
                break;
            case 'datetime':
                $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName} int(10) NOT NULL DEFAULT 0 ";
                $data['i_field_type'] = 'date';
                break;
            case 'editor':
            case 'files':
            case 'images':
                $sql = "ALTER TABLE {$prefixTable} ADD {$fieldName}  MEDIUMTEXT ";
                $data['i_field_type'] = 'string';
                break;
            default:
                $sql = '';
                break;
        }
        if (empty($sql)) {
            $this->error('字段创建失败!');
            return false;
        }
        Db::execute($sql);
        $data['table_name'] = $table;
        $this->isUpdate(false)->allowField(true)->save($data);
        return true;
    }

    /**
     * 删除数据
     */
    public function delData($fid)
    {
        $info = $this->get($fid);
        if (!$info) {
            $this->error = '未找到字段信息';
            return false;
        }
        $prefixTable = config('database.prefix') . $info['table_name']; //表名
        $fields = array_keys(Db::getFields($prefixTable));
        if (in_array($info['field_name'], $fields)) { //先删除表字段
            $sql = "ALTER TABLE " . $prefixTable . " DROP " . $info['field_name'];
            Db::execute($sql);
        }
        $this->destroy($fid);
        return true;
    }

    /**
     * 更新字段缓存
     */
    public function updateCache($mid)
    {
        $fieldList = $this->where('mid', $mid)->order('field_sort')->select();
        $fieldList = obj2array($fieldList);
        $cacheData = [];
        foreach ($fieldList as $field) {
            $cacheData[$field['field_name']] = $field;
        }
        cache('cms_field' . $mid, $cacheData);
        return true;
    }

    /**
     * 内容属性缓存
     */
    public function flagCache($mid)
    {
        $tableName = $this->cmsMoudleModel->where('mid', $mid)->value('table_name');
        $result    = $this->query('DESC ' . config('database.prefix') . $tableName);
        $flag      = [];
        foreach ($result as $field) {
            if ($field['Field'] == 'flag') {
                $tmp  = substr($field['Type'], 4, -2);
                $flag = explode(',', str_replace("'", '', $tmp));
                break;
            }
        }
        cache('cms_flag' . $mid, $flag);
        return true;
    }

    /**
     * 获取属性列表
     * @param $mid
     * @return array
     */
    public function getFlaglist($mid)
    {
        $result = \think\Db::query('DESC ' . config('database.prefix') . $this->cmsMoudleCache[$mid]['table_name']);
        $flag   = [];
        foreach ($result as $v) {
            if ($v['Field'] == 'flag') {
                $tmp  = substr($v['Type'], 4, -2);
                $flag = explode(',', str_replace("'", '', $tmp));
                break;
            }
        }
        return $flag;
    }

    /**
     * 添加属性
     */
    public function addFlag($mid, $value)
    {
        $flag   = $this->getFlaglist($mid); //获取属性
        $flag[] = $value;
        $sql    = "ALTER TABLE " . config('database.prefix') . $this->cmsMoudleCache[$mid]['table_name'] . " MODIFY flag set('" . implode("','", $flag) . "')";
        \think\Db::execute($sql);
        return true;
    }

    /**
     * 修改属性
     */
    public function editFlag($mid, $data)
    {
        if (!empty($data)) {
            $sql = "ALTER TABLE " . config('database.prefix') . $this->cmsMoudleCache[$mid]['table_name'] . " MODIFY flag set('" . implode("','", $data) . "')";
            \think\Db::execute($sql);
            return true;
        }
        $this->error = '没有要修改的数据!';
        return false;
    }

    /**
     * 删除属性
     * @param $index要删除的项目
     * @return bool
     */
    public function delFlag($mid, $index)
    {
        $flag = $this->getFlaglist($mid); //获取属性
        unset($flag[$index]);
        $sql = "ALTER TABLE " . config('database.prefix') . $this->cmsMoudleCache[$mid]['table_name'] . " MODIFY flag set('" . implode("','", $flag) . "')";
        \think\Db::execute($sql);
        return true;
    }
}